package com.dongjiantong.common.utils;/**
 * Created by cao on 2017/12/13.
 */

import org.springframework.core.convert.converter.Converter;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author cao
 * @create 2017-12-13 下午6:32
 **/
public class StringToDateConverter implements Converter<String, Date> {

    private static final String dateFormat      = "yyyy-MM-dd HH:mm:ss";
    private static final String shortDateFormat = "yyyy-MM-dd";

    /**
     * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object)
     */
    @Override
    public Date convert(String source) {
        if (StringUtil.isBlank(source)) {
            return null;
        }
        source = source.trim();
        try {
            if (source.contains("-")) {
                SimpleDateFormat formatter;
//                if (source.contains(":")) {
//                    formatter = new SimpleDateFormat(dateFormat);
//                } else {
//                    formatter = new SimpleDateFormat(shortDateFormat);
//                }
                formatter = new SimpleDateFormat(dateFormat);

                Date dtDate = formatter.parse(source);
                return dtDate;
            } else if (source.matches("^\\d+$")) {
                Long lDate = new Long(source);
                return new Date(lDate);
            }
        } catch (Exception e) {
            throw new RuntimeException(String.format("parser %s to Date fail", source));
        }
        throw new RuntimeException(String.format("parser %s to Date fail", source));
    }
}
